#include "ImageManager.h"

ImageManager::ImageManager()
{
    OriginalImage = NULL;
    WorkingImage = NULL;
    PreviewImage = NULL;
    DisplayableWorkingImage = NULL;
    DisplayablePreviewImage = NULL;
    DefaultImportSize.setHeight(600);
    DefaultImportSize.setWidth(800);
}

void ImageManager::setImportSize(QSize s)
{
    DefaultImportSize = s;
}

void ImageManager::setWorkingImage(QImage *img)
{
    if (WorkingImage != NULL) {
        WorkingImage->detach();
        delete WorkingImage;
    }
    WorkingImage = img;
    rebuildDisplayableWorkingImage();
}

void ImageManager::setPreviewImage(QImage *img)
{
    if (PreviewImage != NULL) {
        PreviewImage->detach();
        delete PreviewImage;
    }

    PreviewImage = img;
    rebuildDisplayablePreviewImage();
}

QImage * ImageManager::getWorkingImage()
{
    return this->WorkingImage;
}

QImage * ImageManager::getPreviewImage()
{
    return this->PreviewImage;
}

QPixmap * ImageManager::getDisplayableWorkingImage()
{
    return DisplayableWorkingImage;
}

QPixmap * ImageManager::getDisplayablePreviewImage()
{
    return DisplayablePreviewImage;
}

void ImageManager::rebuildDisplayableWorkingImage()
{
    if (DisplayableWorkingImage) {
        DisplayableWorkingImage->detach();
        delete DisplayableWorkingImage;
    }
    DisplayableWorkingImage = new QPixmap();
    DisplayableWorkingImage->convertFromImage(*WorkingImage);
}

void ImageManager::rebuildDisplayablePreviewImage()
{
    if (DisplayablePreviewImage) {
        DisplayablePreviewImage->detach();
        delete DisplayablePreviewImage;
    }
    DisplayablePreviewImage = new QPixmap();
    DisplayablePreviewImage->convertFromImage(*PreviewImage);
}

void ImageManager::loadOriginalImageFromFile(QString filepath)
{
    QImage *LoadedImage = new QImage(filepath);
    OriginalImage = new QImage(LoadedImage->scaled(DefaultImportSize, Qt::KeepAspectRatio));
    delete LoadedImage;

    reset();
}

void ImageManager::reset()
{
    setWorkingImage(new QImage(OriginalImage->copy()));
    setPreviewImage(new QImage(OriginalImage->copy()));
    rebuildDisplayableWorkingImage();
    rebuildDisplayablePreviewImage();
}

void ImageManager::resetPreview()
{
    setPreviewImage(new QImage(WorkingImage->copy()));
    rebuildDisplayablePreviewImage();
}

bool ImageManager::isOriginalImageLoaded()
{
    if (OriginalImage != NULL) {
        return true;
    } else {
        return false;
    }

}

void ImageManager::copyWorkingImageToOriginalImage()
{

}

void ImageManager::exportWorkingImage(QString filepath, QImage *img)
{
    if (filepath.isEmpty())
        return;
    else{
        QFile file(filepath);
        if (!file.open(QIODevice::WriteOnly))
        {

            return;
        }
        img->save(filepath);
    }
}
